// pages/user/editProduct/editProduct.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tit:'',
    proImgArr:[],//产品图片数组
    target:'',
    postData:{},//请求数据
    imgPath: [],//图片数组(请求返回的参数)
  },

  //删除产品
  deleteClick:function(){
    var that = this;
    if (that.data.postData.produceId){
      console.log('有produceId');
      wx.showModal({
        title: '提示',
        content: '确定要删除此产品？',
        success(resd) {
          if (resd.confirm) {
            console.log('用户点击确定')
            app.post('pro/deleteProduce', { id: that.data.postData.produceId, openId: wx.getStorageSync('userInfo').userId }).then((res) => {
              console.log('success');
              console.log(res);
              if (res.code == 0) {
                //删除成功
                that.updateBeforeData();
              } else {
                wx.showModal({
                  title: '温馨提示',
                  content: res.msg,
                  showCancel: false,
                })
              }
            }).catch((errMsg) => {
              console.log('fail');
              console.log(errMsg + '失败');
            })
          } else if (resd.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }else{
      console.log('无produceId');
      //删除成功
      that.updateBeforeData();
    }   
  },

  //更新前一页数据并返回(删除)
  updateBeforeData:function(){
    var pages = getCurrentPages();//获取页面栈
    var prevPage = pages[pages.length - 2];//上一页
    var newProductArr = prevPage.data.productArr;
    newProductArr.splice(that.data.target, 1);
    prevPage.setData({
      productArr: newProductArr,
    })
    console.log(prevPage.data.productArr);
    wx.navigateBack();
  },

  //选择产品
  editProductImg:function(){
    var that = this;
    wx.chooseImage({
      count:4,
      success: function (res) {
        console.log(res.tempFilePaths);
        that.setData({
          proImgArr: res.tempFilePaths ,
        })
      },
    })
  },

  //输入信息
  messageInput: function (e) {
    var that = this;
    var data = that.data.postData;
    if (e.currentTarget.id == 0) {
      console.log('品名');
      data['pro_name'] = e.detail.value;
    } else if (e.currentTarget.id == 1) {
      console.log('等级');
      data['level'] = e.detail.value;
    } else if (e.currentTarget.id == 2) {
      console.log('产地');
      data['place'] = e.detail.value;
    } else {
      console.log('规格');
      data['spec'] = e.detail.value;
    }
    that.setData({
      postData: data,
    })
  },


  //保存按钮点击
  savBtnClick: function () {
    var that = this;

    console.log('保存');
    wx.showLoading({
      title: '正在上传图片',
    })
    that.uploadimg({
      url: app.globalData.requestURL + 'file/uploadImg',
      path: that.data.proImgArr,
    })
  },

  //多张图片上传
  uploadimg: function (data) {
    console.log('------------');
    console.log(data.path);
    var that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    wx.uploadFile({
      url: data.url,
      filePath: data.path[i],
      header: {
        compress: '0',
        height: '108',
        width: '100',
      },
      name: 'fileData',
      formData: null,
      success: (resp) => {
        success++;
        console.log(resp.data)
        console.log(i);
        var result = JSON.parse(resp.data);
        if (result.code == 0) {
          that.data.imgPath.push(result.resultData);
        }
      },
      fail: (res) => {
        fail++;
        console.log('fail:' + i + "fail:" + fail);
      },
      complete: () => {
        console.log(i);
        i++;
        if (i == data.path.length) { //当图片传完时，停止调用   
          console.log('执行完毕');
          wx.hideLoading();
          console.log('成功：' + success + " 失败：" + fail);
          //调用上传数据
          console.log(that.data.imgPath);
          that.requestData();//上传数据
        } else {//若图片还没有传完，则继续调用函数
          console.log(i);
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimg(data);
        }
      }
    });
  },

  //请求数据
  requestData:function(){
    var that = this;
    var data = that.data.postData;
    data['pro_img'] = that.data.imgPath.join(",");
    that.setData({
      postData: data,
    })
    app.post('pro/saveOrUpdateProduce', that.data.postData).then((res) => {
      console.log('success');
      console.log(res);
      if (res.code == 0) {
        //更新上一页数据
        var pages = getCurrentPages();//获取页面栈
        var prevPage = pages[pages.length - 2];//上一页
        var newProductArr = prevPage.data.productArr;
        newProductArr[that.data.target].goods_id = res.resultData;
        newProductArr[that.data.target].img = that.data.proImgArr[0];
        prevPage.setData({
          productArr: newProductArr,
        })
        console.log(prevPage.data.productArr);
        wx.navigateBack();
      } else {
        wx.showModal({
          title: '温馨提示',
          content: res.msg,
          showCancel: false,
        })
      }
    }).catch((errMsg) => {
      console.log('fail');
      console.log(errMsg + '失败');
    })
  },

  //选择主营业务
  chooseType: function () {
    wx.navigateTo({
      url: '../timberType/timberType',
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    console.log('编辑页面');
    console.log(options.tit);
    var data = that.data.postData;
    data['openId'] = wx.getStorageSync('userInfo').userId;
    data['produceId'] = options.goods_id;
    that.setData({
      postData: data,
      tit: options.tit,
      target: options.target,
    })

    if (options.goods_id){
      console.log('有produceId');
      app.post('pro/produceInfoByID', { id: that.data.postData.produceId, openId: wx.getStorageSync('userInfo').userId }).then((res) => {
        console.log('success');
        console.log(res);
        if (res.code == 0) {
          //设置拥有店铺
          var that = this;
          var data = that.data.postData;
          data['pro_name'] = res.resultData.pro_name;
          data['level'] = res.resultData.level;
          data['place'] = res.resultData.place;
          data['spec'] = res.resultData.spec;
          data['variety'] = res.resultData.classify;

          var nproImgArr = new Array();
          var arr = res.resultData.pro_img.split(',');
          for(var i=0;i<arr.length;i++){
            var path = app.globalData.imgURL+arr[i];
            nproImgArr.push(path);
          }

          that.setData({
            postData: data,
            proImgArr: nproImgArr,
          })

        } else {
          wx.showModal({
            title: '温馨提示',
            content: res.msg,
            showCancel: false,
          })
        }
      }).catch((errMsg) => {
        console.log('fail');
        console.log(errMsg + '失败');
      })
    }else{
      console.log('没有produceId');
    }
 




  },  

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})